package com.jiexinyun.interceptor;

import com.jiexinyun.utils.uuid.UUID;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 打印日志拦截器
 */
@Slf4j
@Component
public class RequestLoggingInterceptor implements HandlerInterceptor {

    private static final String TRACE_ID = "X-Trace-ID";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 生成或获取Trace ID
        String traceId = request.getHeader(TRACE_ID);
        if (traceId == null || traceId.isEmpty()) {
            traceId = UUID.randomUUID().toString();
        }

        // 存入MDC和请求属性
        MDC.put("traceId", traceId);
        log.info("Request started: {} {}, traceId: {}",
                request.getMethod(),
                request.getRequestURI(),
                traceId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) {
        log.info("Request completed: status={}, traceId={}",
                response.getStatus(),
                MDC.get("traceId"));
        MDC.remove("traceId");
    }
}
